<template>
  <el-dialog
    class="public-dialog"
    title="修改"
    width="615"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div v-loading="loading">
      <VForm
        ref="formRef"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="{ surcharge: surchargeData }"
      >
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'

import { initialUpdate } from '../api'

const props = defineProps({
  select: { type: [Object, String, Number], default: () => {} },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  inline: true,
  labelPosition: 'top',
}

const rules = {
  id: [{ required: true, message: '请选择修改费用项', trigger: 'blur' }],
  cost_amount: [{ required: true, message: '请输入修改金额', trigger: 'blur' }],
  cost_value_diff: [
    {
      required: true,
      message: '请输入修改金额，将自动计算差异金额',
      trigger: 'blur',
    },
  ],
}

const formRef = ref()
const model = ref({})
const loading = ref()
const surchargeData = ref([])

const publicStyle = { style: { width: '244px' } }

const handleChangeId = async e => {
  const _data = surchargeData.value
  const formValues = await formRef.value.getFormValues()
  const _item = _data.find(n => n.value === e)
  model.value = Object.assign({}, formValues, {
    cost_value_old: _item.cost_value || 0,
    finance_initial_bills_surcharge_id: _item.finance_initial_bills_surcharge_id,
  })
  await nextTick()
  calculateDifference()
}

const calculateDifference = async e => {
  const formValues = await formRef.value.getFormValues()
  const { cost_value_old = 0, cost_value = 0 } = formValues
  if (cost_value_old !== undefined && cost_value !== undefined) {
    const diffVal = Math.abs(cost_value_old - cost_value)
    // TODO bigNumber计算
    model.value = Object.assign({}, formValues, {
      cost_value_diff: diffVal,
    })
  } else {
    model.value = Object.assign({}, formValues, {
      cost_value_diff: '',
    })
  }
}

const fieldList = [
  {
    field: 'cost_value_old',
    label: '原始费用金额',
    disabled: true,
    ...publicStyle,
  },
  {
    field: 'cost_ident',
    label: '修改费用项',
    type: 'select',
    originField: 'surcharge',
    ...publicStyle,
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
      onChange: handleChangeId,
    },
  },
  {
    field: 'cost_value',
    label: '修改金额',
    type: 'inputNumber',
    ...publicStyle,
    min: 0,
    max: 999999999999999,
    itemProps: { onChange: calculateDifference },
  },
  {
    field: 'cost_value_diff',
    label: '差异金额',
    type: 'inputNumber',
    ...publicStyle,
    disabled: true,
  },
]

watch(
  () => props.select,
  val => {
    nextTick(() => {
      if (val && props.modelValue) getDetail(val)
    })
  }
)

const getDetail = async rows => {
  try {
    loading.value = true
    // const { channelId } = props
    // const { data } = await transportCostDetail({
    //   finance_initial_bills_id: channelId,
    //   finance_initial_bills_detail_id: id,
    // })

    const { surcharge } = rows
    surchargeData.value = surcharge.map(n => ({
      ...n,
      label: n.cost_label,
      value: n.cost_ident,
    }))
  } catch (e) {
    surchargeData.value = []
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleSave = async () => {
  try {
    const { ...formInfo } = await formRef.value.submit()

    console.warn(formInfo)
    const { code, message } = await initialUpdate({
      ...formInfo,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success('修改成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  surchargeData.value = []
  await nextTick()
  formRef.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
